<template>
  <el-drawer
    ref="drawerBox"
    v-bind="$attrs"
    :wrapper-closable="true"
    :close-on-press-escape="false"
    :title="title"
    :size="showMobilePage?'100%':'80%'"
    append-to-body
    v-on="$listeners"
  >
    <div class="drawer-content">
      <filter-input
        v-model="paramsObj"
        :filter-list="filterList"
        show-search-btn
        line-feed
        @handelClick="queryClick"
        @queryEmpty="queryEmpty"
      />
      <el-tabs v-model="curTabName" type="card" class="contract-detail-tabs-container" style="margin: 8px 0px" @tab-click="onSubActiveOrderChange">
        <el-tab-pane label="项目订单列表" name="all"/>
        <el-tab-pane name="selected">
          <span slot="label">已选择订单<el-badge v-if="projectOrderId" :value="1" /></span>
        </el-tab-pane>
      </el-tabs>
      <div :style="{marginTop: '17px'}" class="table-list">
        <div v-loading="listLoading">
          <u-table
            v-if="(isAllTab && list.items.length > 0) || (isSelectedTab && selectedData.length > 0)"
            ref="projectTableRef"
            :data="curTabName === 'all'?list.items:selectedData"
            :row-class-name="tableRowClassName"
            :height="computedTableHeight"
            :row-height="49"
            :border="true"
            beautify-table
            header-drag-style
            use-virtual
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @select="selectTable"
            @select-all="selectTable"
            @sort-change="sortMethod">
            <u-table-column width="50" align="center" fixed>
              <template slot-scope="scope">
                <el-radio
                  v-model="projectOrderId"
                  :label="scope.row.id"
                  class="custom-table-radio"
                  @change="handleRowChange(scope.row)"
                  @click.native="cancelSelect(scope.row)"
                >{{ '' }}</el-radio>
              </template>
            </u-table-column>
            <u-table-column align="left" label="项目编号" width="180">
              <template slot-scope="scope">
                <div v-if="scope.row.projectNum" :class="{'light-word': scope.row.id}" @click="toOrderDetail(scope.row)">
                  <ToolTip :content="scope.row.projectNum " />
                </div>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="项目名称" width="220">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.projectName" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="品牌名称" width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.brandName" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="标签" width="150">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.tag" type="arr" label-key="name" />
              </template>
            </u-table-column>
            <u-table-column v-if="clientInfoAuth" align="left" label="客户名称" width="220">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.clientName" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="客户性质" width="80">
              <template slot-scope="scope">
                <div v-if="scope.row.customerProperty !== null">{{ scope.row.customerProperty | clientType }}</div>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column v-if="hasRouteAuth('crm:project:incomeData')" align="right" label="含税金额(元)" min-width="130" prop="tax_included_amount" sortable="custom">
              <template slot-scope="scope">
                <PriceColumn :real-val="scope.row.taxAmount" :price="scope.row.taxAmount / 100" />
              </template>
            </u-table-column>
            <u-table-column v-if="hasRouteAuth('crm:project:incomeData')" align="right" label="成本金额(元)" min-width="130" prop="cost" sortable="custom">
              <template slot-scope="scope">
                <PriceColumn :real-val="scope.row.costAmount" :price="scope.row.costAmount / 100" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="核销状态" width="100">
              <template slot-scope="scope">
                <div class="flex">
                  <div :style="scope.row.verificationState === 1?{backgroundColor: '#31CC9C'}:{backgroundColor: '#FD8546'}" class="dot"/>
                  <div>{{ scope.row.verificationState | setVerificationState }}</div>
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="协作人" width="120">
              <template slot-scope="scope">
                <CheckUserInfo
                  v-if="scope.row.cooperation"
                  :user-list="scope.row.cooperation"
                  multiple
                />
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="立项日期" min-width="110" prop="start_project_date" sortable="custom">
              <template slot-scope="scope">
                <div v-if="scope.row.projectApprovalDate">{{ scope.row.projectApprovalDate | standardFormat('YYYY/MM/DD') }}</div>
                <span v-else>--</span>
              </template>
            </u-table-column>
            <u-table-column align="left" label="结案日期" min-width="110" prop="end_project_date" sortable="custom">
              <template slot-scope="scope">
                <div v-if="scope.row.finishDate">{{ scope.row.finishDate | standardFormat('YYYY/MM/DD') }}</div>
                <span v-else>--</span>
              </template>
            </u-table-column>
            <u-table-column align="left" label="状态" width="80">
              <template slot-scope="scope">
                <div class="flex">
                  <div :style="scope.row.projectStatus === 5?{backgroundColor: '#31CC9C'}:{backgroundColor: '#FD8546'}" class="dot"/>
                  <div>{{ scope.row.projectStatus | projectStatus }}</div>
                </div>
              </template>
            </u-table-column>
            <u-table-column v-if="hasRouteAuth('crm:project:privacy')" align="left" label="项目备注" width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.projectRemark" />
              </template>
            </u-table-column>
            <u-table-column v-if="hasRouteAuth('crm:project:privacy')" align="left" label="预计到款" min-width="110" prop="receive_payment_date" sortable="custom">
              <template slot-scope="scope">
                <div v-if="scope.row.receivePayDate">{{ scope.row.receivePayDate | standardFormat('YYYY/MM/DD') }}</div>
                <span v-else>--</span>
              </template>
            </u-table-column>
            <u-table-column align="left" label="所属部门" width="100">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.departmentName" :open-delay="800" class="item" placement="top" effect="dark">
                  <div slot="content" style="max-width: 200px;">
                    {{ (scope.row.attributionMatrixFullName || scope.row.departmentName) }}
                  </div>
                  <div class="ellipsis">{{ scope.row.departmentName }}</div>
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建人" width="110">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.creatorId" :user-id="scope.row.creatorId" :label="scope.row.creator" />
                <span v-else>--</span>
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建时间" min-width="165" prop="create_date" sortable="custom">
              <template slot-scope="scope">
                <div v-if="scope.row.createDate">{{ scope.row.createDate | standardFormat('YYYY/MM/DD HH:mm') }}</div>
                <span v-else>--</span>
              </template>
            </u-table-column>
          </u-table>
          <EmptyPlaceholder v-else style="margin-bottom: 24px" />
        </div>
        <el-row v-if="showMobilePage && isAllTab" type="flex" justify="left">
          <el-pagination
            v-show="list.total > 0"
            :current-page.sync="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :small="true"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <fixed-pagination class="bottom-pagination">
          <div class="delete-button-container">
            <template>
              <el-button :disabled="!projectOrderId" size="small" type="primary" class="related-btn" @click="confirmRelatedOrder">关联订单</el-button>
              <el-button size="small" plain type="primary" class="related-btn" @click="onBackClick">返回</el-button>
            </template>
          </div>
          <el-pagination
            v-if="!showMobilePage"
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes,jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </fixed-pagination>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import { getDepartmentAll } from '@/api/config';
import { getIssueOurTitleList } from '@/api/issueInvoice';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import FilterInput from '@/components/Tool/filter';
import { mapState } from 'vuex';
import { getList } from '@/api/project';
import { hasRouteAuth } from '@/utils/permission';
import { standardFormat } from '@/filters/date';
import { clientType, setVerificationState, projectStatus } from '@/filters/status';
import { getDepartment } from '@/api/project';
import { clientOption, verificationOptions } from '@/views/project/model/selectData';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';

export default {
  name: 'RelatedContract',
  filters: {
    standardFormat,
    projectStatus,
    setVerificationState,
    clientType
  },
  components: {
    FilterInput,
    EmptyPlaceholder
  },
  mixins: [tableSelections, TableAdaptive],
  props: {
    title: {
      type: String,
      default: '选择订单'
    }
  },
  data() {
    return {
      projectOrderId: '',
      projectNum: '',
      paramsObj: {},
      filterInput: {},
      page: 1,
      perPage: 20,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0
      },
      selectedPage: 1,
      selectedPerPage: 20,
      sortType: '',
      sortName: '',
      listLoading: false,
      idKey: 'id', // 多选框参数
      isUmyTable: true,
      tableRefName: 'projectTableRef',
      curTabName: 'all',
      deptTreeList: [],
      selectedData: [],
      subjectOptions: [],
      rangeKeyArr: [{
        attr: 'approvalTime',
        start: 'projectApprovalStart',
        end: 'projectApprovalEnd',
        type: 'time'
      }, {
        attr: 'finishTime',
        start: 'finishStart',
        end: 'finishEnd',
        type: 'time'
      }, {
        attr: 'receivePayTime',
        start: 'receivePayStart',
        end: 'receivePayEnd',
        type: 'time'
      }, {
        attr: 'createTime',
        start: 'createStart',
        end: 'createEnd',
        type: 'time'
      }]
    };
  },
  computed: {
    computedTableHeight() {
      if (!this.orderStatistics || !hasRouteAuth('crm:project:incomeData')) {
        return Number(this.setTableHeight) + 58 + '';
      }
      return this.setTableHeight;
    },
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    clientInfoAuth() {
      return this.hasRouteAuth('crm:projectInfo:clientInfo') || this.isAdmin;
    },
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    tableOutsideHeight() {
      return this.showMobilePage ? 350 : 175;
    },
    isAllTab() {
      return this.curTabName === 'all';
    },
    isSelectedTab() {
      return this.curTabName === 'selected';
    },
    filterList() {
      const dynamicOption = hasRouteAuth('crm:project:privacy') ? [{ keyword: 'receivePayTime', name: '预计到款', labelWidth: '70px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'createTime', name: '创建时间', labelWidth: '96px', timeType: 'daterange', type: 'rangeDate' }] : [{ keyword: 'createTime', name: '创建时间', labelWidth: '70px', timeType: 'daterange', type: 'rangeDate' }];
      const arr = [
        { keyword: 'projectNum', name: '项目编号', labelWidth: '70px', type: 'input' },
        { keyword: 'projectName', name: '项目名称', labelWidth: '96px', type: 'input' },
        { keyword: 'brandName', name: '品牌名称', labelWidth: '70px', type: 'input' },
        { keyword: 'clientName', name: '客户名称', labelWidth: '96px', type: 'input', placeholder: '支持分号搜索多个' },
        { keyword: 'creator', name: '创建人', labelWidth: '70px', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { keyword: 'cooperationName', name: '协作人', labelWidth: '96px', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { keyword: 'projectDirector', name: '项目总监', labelWidth: '70px', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { keyword: 'incomeCreateUser', name: '收入项创建人', labelWidth: '96px', type: 'input', doubleClick: true, placeholder: '请输入，双击填充当前用户' },
        { keyword: 'departmentId', name: '所属部门', type: 'select', isSearch: true, options: this.departmentOption }, // 可搜索下拉
        { keyword: 'customerProperty', name: '客户性质', type: 'select', options: clientOption },
        { keyword: 'verificationState', name: '核销状态', type: 'select', options: verificationOptions },
        { keyword: 'isMyPending', name: '待我处理', type: 'select', options: [
          { value: true, label: '是' }
        ] },
        { keyword: 'relatedInvoice', name: '发票关联状态', type: 'select', options: [{ value: 0, label: '待关联' }, { value: 1, label: '已关联' }] },
        { keyword: 'tag', name: '标签', valueName: 'id', labelName: 'name',
          childrenVal: 'item', type: 'cascaderSelect', checkStrictly: false, options: this.tagTreeList,
          multiple: true, filterable: true, collapseTags: true
        },
        { keyword: 'approvalTime', name: '立项日期', labelWidth: '70px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'finishTime', name: '结案日期', labelWidth: '96px', timeType: 'daterange', type: 'rangeDate' },
        ...dynamicOption
      ];
      return arr;
    },
    selectedTableData() {
      return this.selectedData.slice((this.selectedPage - 1) * this.selectedPerPage, this.selectedPage * this.selectedPerPage);
    }
  },
  created() {
    this.getSubJectOptions();
    this.getDepartmentData();
  },
  methods: {
    hasRouteAuth,
    getSubJectOptions() {
      this.subjectOptions = [];
      getIssueOurTitleList().then(res => {
        if (res.code === 200) {
          res.data.forEach(item => {
            this.subjectOptions.push({
              value: item.id,
              label: item.name,
              isStringVal: true,
              name: '所属公司'
            });
          });
        }
      });
    },
    getDepartmentData() {
      const params = {
        type: 1
      };
      getDepartment(params).then(res => {
        if (res.data) {
          res.data.unshift({ value: -2, label: '--' });
          this.departmentOption = res.data;
        }
      });
    },
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    getParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      if (this.activeName !== '全部') params.projectStatus = this.activeId; // 设置tab
      // 时间处理
      paramsRangeFormat(this.rangeKeyArr, params);
      if (params.tag && params.tag.length > 0) {
        params.tag = params.tag.join(',');
      }
      params.page = this.page;
      params.perPage = this.perPage;
      params.sortName = this.sortName;
      params.sortType = this.sortType;
      return { ...params, ids: this.ids };
    },
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = this.getParams();
      this.listLoading = true;
      delete params.ids;
      getList(params).then(({ data }) => {
        data.items.map(item => {
          if (item.department && item.department.length) item.departmentName = item.department.map(i => i.name).join(',');
          if (item.cooperation && item.cooperation.length) item.cooperationName = item.cooperation.map(i => i.userName).join(',');
          return item;
        });
        this.list = data;
        this.list.isInit = false;
        this.listLoading = false;
        this.page = data.page;
        this.perPage = data.perPage;
        if (this.setSelectRow) this.setSelectRow(data.items);
      }).catch(e => {
        this.listLoading = false;
        console.error(e);
      });
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      if (this.curTabName === 'all') {
        this.fetchData();
      }
    },
    queryClick() {
      if (this.isSelectedTab) this.curTabName = 'all';
      this.fetchData(true);
    },
    queryEmpty() {
      this.sortType = '';
      this.sortName = '';
      this.paramsObj = {};
      this.queryClick();
    },
    handleData(tableData) {
      return tableData.slice((this.selectedPage - 1) * this.selectedPerPage, this.selectedPage * this.selectedPerPage);
    },
    handleSizeChange(val) {
      if (this.curTabName === 'all') {
        this.perPage = val;
        this.fetchData(true);
      } else if (this.isSelectedTab) {
        this.selectedPerPage = val;
        this.setSelectRow(this.selectedTableData);
      }
    },
    handleCurrentChange(toPage) {
      if (this.curTabName === 'all') {
        this.page = toPage;
        this.fetchData();
      } else if (this.isSelectedTab) {
        this.selectedPage = toPage;
        this.setSelectRow(this.selectedTableData);
      }
    },
    // 初始获取数据
    init(data) {
      this.curTabName = 'all';
      this.fetchData();
      this.queryDeptTreeList();
      this.projectOrderId = data.id;
      this.projectNum = data.projectNum;
    },
    // 项目订单列表选中
    handleRowChange(row) {
      if (this.curTabName === 'all') {
        this.projectOrderId = row.id;
        this.projectNum = row.projectNum;
      }
    },
    // 切换列表tab
    onSubActiveOrderChange(data) {
      if (data.paneName === 'all') {
        this.fetchData();
      } else {
        this.projectOrderId && this.querySelectedData();
      }
    },
    // 请求已选中数据
    querySelectedData() {
      this.listLoading = true;
      const params = {};
      params.page = 1;
      params.perPage = 1;
      params.projectNum = this.projectNum;
      getList(params).then(res => {
        this.listLoading = false;
        if (res.code === 200) {
          this.selectedData = res.data.items || [];
        }
      }).catch(_ => {
        this.listLoading = false;
      });
    },
    // 已选择取消选中
    cancelSelect() {
      if (this.curTabName !== 'all') {
        this.projectOrderId = '';
        this.projectNum = '';
        this.selectedData = [];
      }
    },
    // 关联订单
    confirmRelatedOrder() {
      const referenceData = {};
      referenceData.projectOrderId = this.projectOrderId;
      referenceData.projectNum = this.projectNum;
      this.$emit('confirmOrder', referenceData);
      this.onBackClick();
    },
    // 保留数据
    tableSelectionChange(selection) {
      this.selectedData = selection;
      if (this.isSelectedTab) this.setSelectRow(this.selectedTableData);
    },
    onBackClick() {
      this.projectOrderId = '';
      this.projectNum = '';
      this.curTabName = 'all';
      this.selectedData = [];
      this.$refs.drawerBox.closeDrawer();
    },
    toOrderDetail(row) {
      if (row.id) {
        const routeUrl = this.$router.resolve({
          name: 'projectDetail',
          params: { id: row.id }
        });
        window.open(routeUrl.href, '_blank');
      }
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-drawer__header {
  height: 48px;
  padding: 0 12px 0 24px;
  margin: 0;
  box-shadow: 2px 4px 5px 0 rgba(221,225,234,0.3);
  display: flex;
  align-items: center;
  > span {
    font-size: 14px;
    color: #333;
  }
  ::v-deep .el-tabs__nav-wrap::after {
    height: 0 !important;
  }
}
::v-deep .el-tabs__header {
  margin: 0;
  border: none;
}
::v-deep .el-drawer__body {
  overflow-y: auto;
  margin-bottom: 56px;
}
::v-deep .el-drawer__header>span{
  font-size: 16px;
}
::v-deep .el-badge__content{
  background: #FB5227;
}
::v-deep .el-badge__content{
  transform: translateY(5px);
}
.light-word{
  color: #406eff;
  cursor: pointer;
}
.tip {
  color: #999;
  font-size: 13px;
  margin-left: 20px;;
}
.drawer-content {
  padding: 22px 24px 0;
  overflow-y: auto;
  .table-list {
    &::v-deep {
     .el-table__header {
        .el-checkbox__inner {
          position: relative;
          left: -2px;
        }
      }
    }
    border-radius: 10px;
    .el-row {
      padding: 0;
    }
    .delete-button-container {
      flex:1;
      height: 32px;
      display: flex;
      align-items: center;
      .related-btn {
        margin-left: 20px;
        padding-left: 12px;
        padding-right: 12px;
      }
    }
    ::v-deep .pagination-flex {
      position: absolute;
      width: 100% !important;
    }
  }
}
::v-deep .el-tabs__nav-wrap::after {
  z-index: -1;
}
::v-deep .el-tabs__active-bar {
  bottom: 1px;
}
.contract-detail-tabs-container {
  &::v-deep {
    .el-tabs__header  {
      margin-bottom: 0 !important;
      border-bottom: 1px solid #ddd;
      .el-tabs__nav {
        border: none !important;
        height: 32px !important;
      }
      .el-tabs__item {
        padding: 0 12px !important;
        height: 32px !important;
        line-height: 32px !important;
        margin-right: 8px;
        border: 1px solid #ddd;
        border-radius: 4px 4px 0px 0px;
        color: #333;
        background: #f7f8fa;
        font-size: 16px;
        &:last-child {
          margin-right: 0px;
        }
        &.is-active {
          border-bottom-color: #FFFFFF !important;
          font-weight: bold;
          background: #fff;
          color: #406eff;
        }
      }
    }
  }
}
</style>
